<?php

namespace JsonLowCode;

use JsonLowCode\Helps\Random;
use JsonLowCode\Support\Fluent;
use JsonLowCode\Traits\HasMake;

/**
 * 组件注册映射
 */
class Map extends Fluent
{
    use HasMake;

    public function __construct(array|callable $args = null)
    {
        parent::__construct();
        if ($args!=null){
            if (is_array($args)){
                $this->attributes = $args;
            }
            if (is_callable($args)){
                call_user_func($args, $this);
            }
        }
    }

    /**
     * 映射类型
     * @param string $type  sfc=映射vue单文件 | api=远程映射vue-sfc | package= 包组件映射
     * @return $this
     */
    public function type(string $type = 'api' | 'sfc'  | 'package'): static
    {
        $this->attributes['type'] = $type;
        return $this;
    }

    /**
     * 组件名称
     * @param string $name
     * @return $this
     */
    public function name(string $name): static
    {
        $this->attributes['componentName'] = ucfirst($name);
        return $this;
    }

    /**
     * api=远程映射vue-sfc 类型
     * @param string $name 组件名称
     * @param string $url 远程sfc请求url 必须是.vue结尾
     * @return $this
     */
    public function api(string $name, string $url): static
    {
        $this->name($name)->type('api');
        $this->attributes['url'] = $url;
        return $this;
    }

    /**
     * tpl=映射vue单文件
     * @param string $name 组件名称
     * @param string $view 视图字符串
     * @return $this
     */
    public function sfc(string $name, string $view): static
    {
        $this->name($name)->type('sfc');
        $this->attributes['path'] = Random::alpha().$name.".vue";
        if (isSfcView($view)){
            $this->attributes['tpl'] = $view;
        }else{
            $this->attributes['tpl'] =  "<template>{$view}</template>";
        }
        return $this;
    }

    /**
     * package= 包组件映射
     * @param string $package 包名
     * @param string $version 包版本
     * @param string $componentName 组件名称
     * @param string $exportName 导出名称
     * @return $this
     */
    public function package(string $package, string $version, string $componentName, string $exportName = ""): static
    {
        $this->attributes['package'] = $package;
        $this->attributes['componentName'] = $componentName;
        $this->attributes['destructuring'] = true;
        $this->attributes['version'] = $version;
        $this->attributes['exportName'] = $exportName?:$componentName;
        return $this;
    }
}
